//
//  StoreListTableView.swift
//  koolcar
//
//  Created by kuaimaxiansheng on 2023/10/25.
//

import UIKit
import MJRefresh
import SkeletonView

class StoreListTableView: BaseTableView {
    var emptyView: LYEmptyView!
    var pageNum: NSInteger = 1
    var dataArray = NSMutableArray()
    var categoryId = -1
    var promotionId = -1//活动ID
    var isFlashMore = false
    var promotionModel: PromotionCotentModel!
    override init(frame: CGRect, style: UITableViewStyle) {
        super.init(frame: frame, style: style)
        self.backgroundColor = Theme.viewBkgGrayColor
        self.delegate = self
        self.dataSource = self
        self.separatorStyle = .none
        self.rowHeight = UITableViewAutomaticDimension
        self.estimatedRowHeight = 120
        self.register(FlashSaleTableViewCell.self, forCellReuseIdentifier: "FlashSaleTableViewCell")
        self.register(StoreListTableViewCell.self, forCellReuseIdentifier: "StoreListTableViewCell")
        self.register(SkeletonTableCell.self, forCellReuseIdentifier: "SkeletonTableCell")
        self.setUpNoData()
        
        self.isSkeletonable = true
        self.addPullRefreash()
        self.addLoadMoreRefreash()
        self.showAnimatedSkeleton()
        //限时抢购结束
        NotificationCenter.default.addObserver(self, selector: #selector(timeEndRefreash), name: NSNotification.Name("mainRefreash"), object: nil)
    }
    
    deinit {
        NotificationCenter.default.removeObserver(self)
    }
    
    
    required init?(coder: NSCoder) {
        fatalError("init(coder:) has not been implemented")
    }
    
    
    //MARK: - 下拉刷新
    func addPullRefreash()  {
        self.mj_header = MJRefreshNormalHeader.init(refreshingBlock: {[weak self] in
            self?.pageNum = 1
            self?.sendDataRequest(isMore: false)
           
        })
    }
    
    //MARK: - 上拉加载更多
    private func addLoadMoreRefreash()  {
        weak var weakself = self
        let tempFooter = ExtNoMoreRefreashFooterView.init(refreshingBlock: {
            weakself?.pageNum = weakself!.pageNum + 1
            self.sendDataRequest(isMore: true)
            self.mj_footer.endRefreshing()
        })
        self.mj_footer = tempFooter
    }
    
    func sendDataRequest(isMore: Bool){
        if self.isFlashMore == true {
            self.requestFlashCaleData()
        }
        self.requestGetProductList(isMore: false)
    }
    
    ///空视图
    func setUpNoData() {
        self.emptyView = LYEmptyView.emptyActionView(withImageStr: "icon_empty", titleStr: MMLocalizedString("no_more_data", comment: "暂时没有数据"), detailStr: "", btnTitleStr: "") {
            
        }
        emptyView?.subViewMargin = 28;
        emptyView?.contentViewOffset = -50
        self.ly_emptyView = self.emptyView
    }
    
    
    //MARK: - Request
    //获取商品列表
    func requestGetProductList(isMore: Bool) {
        UIApplication.shared.keyWindow?.showLoadingHUDText(nil)
        var param = NSMutableDictionary() as! [String : String]//"ascOrDesc": 1：升序，2：降序
        if self.categoryId != -1{
            param["categoryId"] = "\(self.categoryId)"
        }
        param["pageNumber"] = "\(self.pageNum)"
        param["pageSize"] = "10"
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.getProductList(param: param), objectType: ProductModel.self) { data in
            self.mj_header?.endRefreshing()
            self.mj_footer?.endRefreshing()
            UIApplication.shared.keyWindow?.handleLoading()
            let resultObj = data as! ProductModel
            if resultObj.code == "1" {
                if self.pageNum == 1 {
                    self.dataArray.removeAllObjects()
                }
                let dataContent = resultObj.data?.content ?? []
                if dataContent.count < 10 {
                    self.mj_footer?.endRefreshingWithNoMoreData()
                }
                self.dataArray.addObjects(from: dataContent)
            }else{
                self.makeToastBottom(message: resultObj.msg ?? "")
            }
            
            if self.dataArray.count == 0 {
                self.mj_footer.isHidden = true
            }else{
                self.mj_footer.isHidden = false
            }
            //收藏
            self.dataArray.map{$0 as? VehicleLisetModel}.forEach { item in
                item?.favoriteBlock = { [weak self] in
                    self?.requestFavorite(model: item!)
                }
            }
            self.willShowSketchView()
            self.reloadData()
        } error: { err in
            self.willShowSketchView()
            UIApplication.shared.keyWindow?.handleLoading()
            self.mj_header?.endRefreshing()
            self.mj_footer?.endRefreshing()
            self.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    private func willShowSketchView(){
        if self.dataArray.count > 0 || self.promotionModel != nil {
            self.emptyView.isHidden = true
        }else{
            self.emptyView.isHidden = false
        }
        self.hideSkeleton()
    }
    
    //限时抢购-更多-分页列表
    func requestGetMoreFlashSaleList(isMore: Bool) {
        UIApplication.shared.keyWindow?.showLoadingHUDText(nil)
        var param = NSMutableDictionary() as! [String : String]//"ascOrDesc": 1：升序，2：降序
        if self.categoryId != -1{
            param["categoryId"] = "\(self.categoryId)"
        }
        param["promotionId"] = "\(self.promotionId)"
        param["pageNumber"] = "\(self.pageNum)"
        param["pageSize"] = "10"
        
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.moreFlashSaleList(param: param), objectType: MoreFlashSaleModel.self) { data in
            self.mj_header?.endRefreshing()
            self.mj_footer?.endRefreshing()
            UIApplication.shared.keyWindow?.handleLoading()
            let resultObj = data as! MoreFlashSaleModel
            if resultObj.code == "1" {
                if isMore == false {
                    self.dataArray.removeAllObjects()
                }
                let dataContent = resultObj.data?.page?.content ?? []
                if dataContent.count < 10 {
                    self.mj_footer?.endRefreshingWithNoMoreData()
                }
                self.dataArray.addObjects(from: dataContent)
            }else{
                self.makeToastBottom(message: resultObj.msg ?? "")
            }
            
//            if self.dataArray.count == 0 {
//                self.setUpNoData()
//                self.mj_footer.isHidden = true
//            }else{
//                self.mj_footer.isHidden = false
//            }
            self.willShowSketchView()
            //分享连接
            XTManageCenter.setLocalDataString(aKey: "shareText", aValue: resultObj.data?.shareText ?? "")
            
            //收藏
            self.dataArray.map{$0 as? VehicleLisetModel}.forEach { item in
                item?.favoriteBlock = { [weak self] in
                    self?.requestFavorite(model: item!)
                }
            }
            self.reloadData()
        } error: { err in
            UIApplication.shared.keyWindow?.handleLoading()
            self.mj_header?.endRefreshing()
            self.mj_footer?.endRefreshing()
            self.makeToastBottom(message: err?.domain ?? "")
        }
    }
    
    ///限时抢购
    func requestFlashCaleData(){
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.flashCale, objectType: FlashCaleModel.self) { data in
            let resultObj = data as! FlashCaleModel
            if resultObj.code == "1" {
                let promotionModel = resultObj.data?.promotion
                self.promotionModel = promotionModel
            }
            self.willShowSketchView()
            self.reloadData()
        } error: { err in
            self.willShowSketchView()
        }
    }
    
    
    ///收藏取消收藏
    func requestFavorite(model: VehicleLisetModel){
        if UserModule.shared.isLogined == false{
            self.jumpToLogin()
            return
        }
        let param = ["productId": "\(model.id ?? 0)"]
        XTRequestCenter.shared.sendRequestMappableTargetObject(target: APIManager.favoriteProduct(param: param),objectType: CommondResModel.self) { data in
            let resultObj = data as! CommondResModel
            if resultObj.code == "1" {
                if model.isFavorite == false {
                    self.makeToast(message: MMLocalizedString("successful_collection", comment: "收藏成功"))
                    model.isFavorite = true
                }else{
                    self.makeToast(message: MMLocalizedString("uncollected", comment: "已取消收藏"))
                    model.isFavorite = false
                }
                self.reloadData()
                //延迟
//                DispatchQueue.main.asyncAfter(deadline: .now() + 2) {
//                    self.requestGetProductList(isMore: false)
//                }
            }else{
                self.makeToast(message: resultObj.msg ?? "")
            }
        }error: { err in
            
        }
    }
    
    
    func jumpToLogin(){
        guard let tabbarVC = UIApplication.shared.keyWindow?.rootViewController as? BaseTabbarController else {
            return
        }
        let vc = LoginViewController()
        let loginNavi = BaseNavigationController.init(rootViewController: vc)
        loginNavi.modalPresentationStyle = .fullScreen
        tabbarVC.present(loginNavi, animated: true)
    }
    
    @objc func roadRefreash(){
        if self.dataArray.count > 0 {
            return
        }
        if self.isFlashMore == false{
            self.requestFlashCaleData()
        }else {
            self.pageNum = 1
            self.requestGetMoreFlashSaleList(isMore: false)
        }
    }
    
   @objc func timeEndRefreash(){
       if self.isFlashMore == false{
           self.requestFlashCaleData()
       }else {
           self.pageNum = 1
           self.requestGetMoreFlashSaleList(isMore: false)
       }
    }
    
}

extension StoreListTableView: SkeletonTableViewDelegate, SkeletonTableViewDataSource {
    
    func numSections(in collectionSkeletonView: UITableView) -> Int {
        return 1
    }
    
    func collectionSkeletonView(_ skeletonView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 10
    }
    
    func collectionSkeletonView(_ skeletonView: UITableView, cellIdentifierForRowAt indexPath: IndexPath) -> ReusableCellIdentifier {
        return "SkeletonTableCell"
    }
    
    func collectionSkeletonView(_ skeletonView: UITableView, skeletonCellForRowAt indexPath: IndexPath) -> UITableViewCell? {
        let cell = skeletonView.dequeueReusableCell(withIdentifier: "SkeletonTableCell", for: indexPath) as! SkeletonTableCell
        cell.clipsToBounds = true
        
        return cell
    }
    
    //
    func numberOfSections(in tableView: UITableView) -> Int {
        if self.dataArray.count == 0 && self.promotionModel == nil {
            return 0
        }
        return 2
    }
    
    func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        return 1
    }
    
    func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if (self.promotionModel?.products ?? []).count == 0 && indexPath.section == 0{
            return 0.01
        }
        return UITableViewAutomaticDimension
    }
    
    func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        return 10
    }
    
    
    func tableView(_ tableView: UITableView, heightForFooterInSection section: Int) -> CGFloat {
        return 0.1
    }
    
    func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        let header = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenHeight, height: 10))
        header.backgroundColor = Theme.whiteColor
        if self.isFlashMore == true{
            header.backgroundColor = .white
        }
        
        return header
    }
    
    func tableView(_ tableView: UITableView, viewForFooterInSection section: Int) -> UIView? {
        let footer = UIView.init(frame: CGRect.init(x: 0, y: 0, width: kScreenHeight, height: 0.1))
        return footer
    }
    
    func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        
        if indexPath.section == 0 {
            //限时抢购
            let cell = tableView.dequeueReusableCell(withIdentifier: "FlashSaleTableViewCell", for: indexPath) as! FlashSaleTableViewCell
            cell.setSaleModel(saleModel: self.promotionModel)
            return cell
        }else{
            let cell = tableView.dequeueReusableCell(withIdentifier: "StoreListTableViewCell", for: indexPath) as! StoreListTableViewCell
            if self.dataArray.count > 0{
                cell.promotionId = self.promotionId
                cell.setData(data: self.dataArray as! [VehicleLisetModel])
            }
            return cell
        }
    }
    
    
}
